package com.kakavr.util;

import java.io.File;
import java.util.Arrays;

import org.joda.time.DateTimeUtils;
import org.springframework.web.multipart.MultipartFile;

import com.kakavr.base.log.BaseLog;

public class AttachUtils extends BaseLog {
	// 扩展名类型
	private static final String EXT_FILE = "gif,jpg,jpeg,png,bmp,swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,rm,rmvb";

	private static String resource = "/opt/nginx/html/uploads/";
	
	/**
	 * 判断文件是否是允许的类型
	 * 
	 * @param fileExt
	 * @param dirName
	 * @return
	 */
	public static boolean isPermit(String fileExt) {
		return Arrays.asList(EXT_FILE.split(",")).contains(fileExt);
	}
	
	public static String uploadFile(MultipartFile file){
		long dateTime = DateTimeUtils.currentTimeMillis();
		String fileName = file.getOriginalFilename().replaceAll("\\+", "");
		String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
		if (! isPermit(fileType.toLowerCase())){
			return "error";
		}
		fileName = dateTime+"."+fileType;
		File filepath = new File(resource,fileName);
		//判断路径是否存在，如果不存在就创建一个
        if (!filepath.exists()) { 
            filepath.mkdirs();
        }
      //将上传文件保存到一个目标文件当中
        try {
			file.transferTo(filepath);
		} catch (Exception e) {
			serror("上传文件出错，错误信息："+e);
			return "error";
		}
        return "/uploads/"+fileName;
	}


}
